package mq.rabbit.common.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static mq.rabbit.common.config.RabbitMQ.*;

/**
 * @Description: 工具类
 * @Author Ray
 * @Date 2021/03/05 16:20
 * @Version 1.0
 */
public class RabbitMQUtils {

    private static ConnectionFactory connectionFactory;

    // 类加载时候只执行一次
    static {
        connectionFactory = new ConnectionFactory();
    }

    // 定义提供连接对象的方法
    public static Connection getConnection() {

        try {
            // 设置连接mq主机
            connectionFactory.setHost(HOST);
            // 设置端口号
            connectionFactory.setPort(PORT);
            // 设置连接哪个虚拟主机
            connectionFactory.setVirtualHost(V_HOSTS);
            // 设置访问虚拟主机的用户名和密码
            connectionFactory.setUsername(USERNAME);
            connectionFactory.setPassword(PASSWORD);

            // 通道绑定对应消息队列
            return connectionFactory.newConnection();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 关闭通道和关闭连接的方法
    public static void closeChanelAndConnection(Channel channel, Connection connection) {
        try {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}